package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.MaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.ThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
@Transactional
public class MaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements MaterialService {
    @Autowired
    private MinIOFileStorageService minIOFileStorageService;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(MaterialDto dto) {
        //1处理数据：校验+处理
        //1.1校验参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.2处理参数，page，size设置默认值
        dto.checkParam();
        //2.业务处理：分页查询
        //2.1设置分页
        IPage page = new Page(dto.getPage(),dto.getSize());
        //2.2设置查询参数
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.3设置类型过滤
        if(dto.getIsCollection() == WmMaterial.CollectionStatus.IS_COLLECTION.getCode()){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //2.4设置用户过滤
        lambdaQueryWrapper.eq(WmMaterial::getUserId,ThreadLocalUtil.get());
        //2.5 排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        page =  page(page,lambdaQueryWrapper);
        //3.返回数据
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int) page.getTotal());
        return pageResponseResult.ok(page.getRecords());
    }

    /**
     * 素材上传
     *
     * @param multipartFile@return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.处理图片数据
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传
        //2.1 处理文件名称
        String path = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        //2.2上传
        try  {
            InputStream inputStream = multipartFile.getInputStream();
            String url = minIOFileStorageService.uploadImgFile("", path + type, inputStream);
            //3.插入数据库
            WmMaterial wmMaterial = WmMaterial.builder()
                    .isCollection(WmMaterial.CollectionStatus.NOT_COLLECTION.getCode())
                    .userId(ThreadLocalUtil.get())
                    .type(WmMaterial.TypeStatus.IMAGE.getCode())
                    .createdTime(new Date())
                    .url(url)
                    .build();
            save(wmMaterial);
            //4.返回
            return ResponseResult.okResult(wmMaterial);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        WmNewsMaterial wmNewsMaterial = wmNewsMaterialMapper.selectOne(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(wmNewsMaterial != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"素材已绑定文章，无法删除");
        }
        minIOFileStorageService.delete(getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId,id)).getUrl());
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
